package com.sky.lightleafpicturepavilionserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.lightleafpicturepavilionserver.domain.HomeBanner;
import com.sky.lightleafpicturepavilionserver.dto.HomeBannerDTO;
import com.sky.lightleafpicturepavilionserver.service.HomeBannerService;
import com.sky.lightleafpicturepavilionserver.mapper.HomeBannerMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【home_banner(首页Banner轮播图表)】的数据库操作Service实现
* @createDate 2025-09-30 20:16:58
*/
@Slf4j
@Service
public class HomeBannerServiceImpl extends ServiceImpl<HomeBannerMapper, HomeBanner>
    implements HomeBannerService{

    /**
     * 获取首页Banner列表（固定5个）
     * @return Banner列表
     */
    @Override
    public List<HomeBannerDTO> getHomeBannerList() {
        log.info("获取首页Banner列表");
        
        LocalDateTime now = LocalDateTime.now();
        
        // 查询条件：状态启用、在展示时间范围内
        LambdaQueryWrapper<HomeBanner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HomeBanner::getStatus, 1)  // 状态启用
                .and(wrapper -> wrapper
                        .isNull(HomeBanner::getStartTime)  // 开始时间为空
                        .or()
                        .le(HomeBanner::getStartTime, now)  // 或者开始时间小于等于当前时间
                )
                .and(wrapper -> wrapper
                        .isNull(HomeBanner::getEndTime)  // 结束时间为空
                        .or()
                        .ge(HomeBanner::getEndTime, now)  // 或者结束时间大于等于当前时间
                )
                .orderByDesc(HomeBanner::getSortOrder)  // 按排序权重降序
                .orderByDesc(HomeBanner::getCreateTime)  // 再按创建时间降序
                .last("LIMIT 5");  // 限制5条记录
        
        List<HomeBanner> bannerList = this.list(queryWrapper);
        
        // 转换为DTO
        List<HomeBannerDTO> result = bannerList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        log.info("获取到{}个Banner", result.size());
        return result;
    }
    
    /**
     * 实体转DTO
     */
    private HomeBannerDTO convertToDTO(HomeBanner banner) {
        return HomeBannerDTO.builder()
                .id(banner.getId())
                .title(banner.getTitle())
                .imageUrl(banner.getImageUrl())
                .jumpUrl("/pages/category/index")  // 固定跳转到壁纸分类大全页面
                .sortOrder(banner.getSortOrder())
                .build();
    }
}




